from PySide6.QtWidgets import QTreeWidget, QTreeWidgetItem, QMenu, QInputDialog, QDialog, QVBoxLayout, QHBoxLayout, QLabel, QComboBox, QLineEdit, QPushButton, QFormLayout, QWidget
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QIcon
from .manager import SessionManager
from logger.manager import LogManager
import os
import serial.tools.list_ports
from datetime import datetime
from theme.manager import ThemeManager

class SessionTree(QTreeWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.session_manager = SessionManager()
        self.log_manager = LogManager()
        self.theme_manager = ThemeManager()
        self.app_log = self.log_manager.get_log_file_path('app')
        self.setObjectName('session_list')
        self.setup_ui()
        self.setup_icons()
        self.init_root_node()
        self.load_sessions()
        self.setup_context_menu()
        
    def setup_ui(self):
        """初始化UI"""
        # 设置树形控件属性
        self.setHeaderHidden(True)  # 隐藏表头
        self.setColumnCount(1)  # 设置列数为1
        self.setDragEnabled(True)  # 启用拖拽
        self.setAcceptDrops(True)  # 接受拖放
        self.setDropIndicatorShown(True)  # 显示拖放指示器
        self.setSelectionMode(QTreeWidget.SelectionMode.SingleSelection)  # 单选模式
        
        # 创建展开和折叠按钮
        self.expand_button = QPushButton("", self)
        self.expand_button.setFixedSize(QSize(16, 16))
        self.collapse_button = QPushButton("", self)
        self.collapse_button.setFixedSize(QSize(16, 16))
        
        # 设置按钮样式
        self.expand_button.setObjectName("expand_button")
        self.collapse_button.setObjectName("collapse_button")
        
        # 连接按钮信号
        self.expand_button.clicked.connect(self.expand_all_sessions)
        self.collapse_button.clicked.connect(self.collapse_all_sessions)
        
        # 创建按钮布局
        button_layout = QHBoxLayout()
        button_layout.addStretch(1)  # 添加弹性空间，将按钮推到右侧
        button_layout.addWidget(self.expand_button)
        button_layout.addWidget(self.collapse_button)
        button_layout.setContentsMargins(10, 5, 10, 5)
        button_layout.setAlignment(Qt.AlignmentFlag.AlignRight)  # 设置右对齐
        
        # 创建主布局
        main_layout = QVBoxLayout(self)
        main_layout.addLayout(button_layout)
        main_layout.addWidget(self.viewport())
        main_layout.setContentsMargins(0, 0, 0, 0)
        
    def expand_all_sessions(self):
        """展开所有会话"""
        def expand_recursive(item):
            item.setExpanded(True)
            for i in range(item.childCount()):
                expand_recursive(item.child(i))
        
        root = self.topLevelItem(0)
        if root:
            expand_recursive(root)
            
    def collapse_all_sessions(self):
        """折叠所有会话"""
        def collapse_recursive(item):
            item.setExpanded(False)
            for i in range(item.childCount()):
                collapse_recursive(item.child(i))
        
        root = self.topLevelItem(0)
        if root:
            collapse_recursive(root)
            root.setExpanded(True)  # 保持根节点展开
        
    def filter_sessions(self, text):
        """根据搜索文本过滤会话"""
        root = self.topLevelItem(0)
        self._filter_tree_items(root, text.lower())
        root.setExpanded(True)
        
    def _filter_tree_items(self, item, text):
        """递归过滤树形结构中的项目"""
        visible = False
        
        # 如果是会话节点，检查名称是否匹配
        if item.data(0, Qt.ItemDataRole.UserRole) and \
           item.data(0, Qt.ItemDataRole.UserRole)['config']['type'] == 'session':
            visible = text == '' or text in item.text(0).lower()
            item.setHidden(not visible)
            return visible
        
        # 如果是文件夹节点，递归检查子节点
        for i in range(item.childCount()):
            child_visible = self._filter_tree_items(item.child(i), text)
            visible = visible or child_visible
        
        # 如果不是根节点，根据子节点的可见性决定是否显示
        if item != self.topLevelItem(0):
            item.setHidden(not visible)
        
        return visible

    def setup_icons(self):
        """设置图标资源"""
        # 获取当前主题
        theme_manager = ThemeManager()
        current_theme = theme_manager.get_current_theme()
        theme_suffix = "light" if "light" in current_theme.lower() else "dark"  # 'light' 或 'dark'
        
        # 获取图标文件的绝对路径
        icons_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons')
        folder_icon_path = os.path.join(icons_dir, f'folder-{theme_suffix}.png')
        computer_icon_path = os.path.join(icons_dir, f'computer-{theme_suffix}.png')
        expand_icon_path = os.path.join(icons_dir, f'expand-{theme_suffix}.png')
        collapse_icon_path = os.path.join(icons_dir, f'collapse-{theme_suffix}.png')

        # 创建图标并设置大小
        icon_size = QSize(16, 16)
        self.folder_icon = QIcon(folder_icon_path)
        self.serial_icon = QIcon(computer_icon_path)
        self.ssh_icon = QIcon(computer_icon_path)
        self.telnet_icon = QIcon(computer_icon_path)
        
        # 设置展开和折叠按钮的图标
        self.expand_button.setIcon(QIcon(expand_icon_path))
        self.collapse_button.setIcon(QIcon(collapse_icon_path))
        self.expand_button.setIconSize(QSize(16, 16))
        self.collapse_button.setIconSize(QSize(16, 16))
        
        # 设置按钮提示文本
        self.expand_button.setToolTip("展开全部")
        self.collapse_button.setToolTip("折叠全部")

        # 设置图标大小
        self.setIconSize(icon_size)

    def update_icons(self, computer_icon, folder_icon):
        """更新会话树的图标"""
        # 更新实例的图标
        self.folder_icon = folder_icon
        self.serial_icon = computer_icon
        self.ssh_icon = computer_icon
        self.telnet_icon = computer_icon
        
        # 获取当前主题类型
        theme_type = "light" if "light" in self.theme_manager.get_current_theme().lower() else "dark"
        
        # 更新展开和折叠按钮图标
        icons_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons')
        expand_icon_path = os.path.join(icons_dir, f'expand-{theme_type}.png')
        collapse_icon_path = os.path.join(icons_dir, f'collapse-{theme_type}.png')
        
        self.expand_button.setIcon(QIcon(expand_icon_path))
        self.collapse_button.setIcon(QIcon(collapse_icon_path))
        
        # 更新所有节点的图标
        def update_node_icons(item):
            # 获取节点数据
            session_data = item.data(0, Qt.ItemDataRole.UserRole)
            
            # 根据节点类型设置图标
            if session_data and session_data['config']['type'] == 'session':
                session_type = session_data['config'].get('session_type', '')
                if session_type == "串口":
                    item.setIcon(0, self.serial_icon)
                elif session_type == "SSH":
                    item.setIcon(0, self.ssh_icon)
                elif session_type == "Telnet":
                    item.setIcon(0, self.telnet_icon)
            else:
                item.setIcon(0, self.folder_icon)
            
            # 递归更新子节点
            for i in range(item.childCount()):
                update_node_icons(item.child(i))
        
        # 从根节点开始更新
        root = self.topLevelItem(0)
        if root:
            update_node_icons(root)
        
    def init_root_node(self):
        """初始化根节点"""
        root = QTreeWidgetItem(self)
        root.setText(0, "所有会话")
        root.setFlags(root.flags() & ~Qt.ItemFlag.ItemIsEditable)  # 设置根节点不可编辑
        root.setIcon(0, self.folder_icon)  # 设置根节点图标
        self.addTopLevelItem(root)
        root.setExpanded(True)
        
    def load_sessions(self):
        """加载会话到树形结构"""
        sessions_data = self.session_manager.load_sessions()
        root = self.topLevelItem(0)
        
        # 先创建所有目录结构
        if 'directories' in sessions_data:
            for dir_path in sessions_data['directories']:
                path_parts = dir_path.split(os.sep)
                current_parent = root
                
                # 创建或查找父节点
                for part in path_parts:
                    found = False
                    for j in range(current_parent.childCount()):
                        child = current_parent.child(j)
                        if child.text(0) == part:
                            current_parent = child
                            found = True
                            break
                    if not found:
                        new_item = QTreeWidgetItem(current_parent)
                        new_item.setText(0, part)
                        new_item.setIcon(0, self.folder_icon)  # 设置文件夹图标
                        current_parent = new_item
        
        # 然后添加所有会话
        if 'sessions' in sessions_data:
            for session in sessions_data['sessions']:
                path_parts = session['path'].split(os.sep)
                current_parent = root
                
                # 创建或查找父节点
                for i, part in enumerate(path_parts[:-1]):
                    found = False
                    for j in range(current_parent.childCount()):
                        child = current_parent.child(j)
                        if child.text(0) == part:
                            current_parent = child
                            found = True
                            break
                    if not found:
                        new_item = QTreeWidgetItem(current_parent)
                        new_item.setText(0, part)
                        new_item.setIcon(0, self.folder_icon)  # 设置文件夹图标
                        current_parent = new_item
                
                # 添加当前会话节点
                item = QTreeWidgetItem(current_parent)
                # 确保显示名称不包含.json后缀
                display_name = session['config']['name'].replace('.json', '')
                item.setText(0, display_name)
                
                # 根据会话类型设置图标
                session_type = session['config'].get('session_type', '')
                if session_type == "串口":
                    item.setIcon(0, self.serial_icon)
                elif session_type == "SSH":
                    item.setIcon(0, self.ssh_icon)
                elif session_type == "Telnet":
                    item.setIcon(0, self.telnet_icon)
                # 确保会话数据包含正确的类型信息
                session_data = {
                    'path': session['path'],
                    'config': {
                        'name': session['config']['name'],
                        'type': session['config'].get('type', 'session'),  # 默认为session类型
                        'session_type': session['config'].get('session_type', ''),
                        'session_params': session['config'].get('session_params', {})
                    }
                }
                item.setData(0, Qt.ItemDataRole.UserRole, session_data)
        
        # 加载完成后展开所有节点
        self.expand_all_sessions()
            
    def setup_context_menu(self):
        """设置右键菜单"""
        self.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
        self.customContextMenuRequested.connect(self.show_context_menu)
        
    def show_context_menu(self, position):
        """显示右键菜单"""
        item = self.itemAt(position)
        menu = QMenu(self)
        
        if item is None or item == self.topLevelItem(0):
            # 仅在根节点或空白处显示新建文件夹选项
            create_folder_action = menu.addAction("新建分组")
            create_folder_action.triggered.connect(lambda: self.create_new_folder(self.topLevelItem(0)))
        else:
            session_data = item.data(0, Qt.ItemDataRole.UserRole)
            is_session = session_data and session_data['config']['type'] == 'session'
            
            if not is_session:
                create_folder_action = menu.addAction("新建分组")
                create_session_action = menu.addAction("新建会话")
                create_folder_action.triggered.connect(lambda: self.create_new_folder(item))
                create_session_action.triggered.connect(lambda: self.create_new_session(item))
                menu.addSeparator()
            
            rename_action = menu.addAction("重命名")
            edit_action = menu.addAction("编辑参数")
            delete_action = menu.addAction("删除")
            
            rename_action.triggered.connect(lambda: self.rename_item(item))
            edit_action.triggered.connect(lambda: self.edit_session_params(item))
            delete_action.triggered.connect(lambda: self.delete_item(item))
            
            # 如果不是会话节点，禁用编辑参数选项
            if session_data and session_data['config']['type'] == 'session':
                edit_action.setEnabled(True)
            else:
                edit_action.setEnabled(False)
        
        menu.exec(self.mapToGlobal(position))

    def edit_session_params(self, item):
        """编辑会话参数"""
        session_data = item.data(0, Qt.ItemDataRole.UserRole)
        if not session_data:
            return
            
        params_dialog = SessionParamsDialog(self)
        # 设置当前会话类型和参数
        params_dialog.type_combo.setCurrentText(session_data['config']['session_type'])
        
        # 根据会话类型设置当前参数
        session_type = session_data['config']['session_type']
        params = session_data['config']['session_params']
        
        if session_type == "串口":
            params_dialog.port.setCurrentText(params.get('port', ''))
            params_dialog.baudRate.setCurrentText(params.get('baudRate', '9600'))
        elif session_type == "SSH":
            params_dialog.host.setText(params.get('host', ''))
            params_dialog.port.setText(params.get('port', '22'))
            params_dialog.username.setText(params.get('username', ''))
            params_dialog.password.setText(params.get('password', ''))
        elif session_type == "Telnet":
            params_dialog.host.setText(params.get('host', ''))
            params_dialog.port.setText(params.get('port', '23'))
            
        if params_dialog.exec() == QDialog.DialogCode.Accepted:
            new_type, new_params = params_dialog.get_session_params()
            
            try:
                # 更新配置文件
                config_file = os.path.join(self.session_manager.sessions_dir, session_data['path'])
                with open(config_file, 'r', encoding='utf-8') as f:
                    config = json.load(f)
                
                config['session_type'] = new_type
                config['session_params'] = new_params
                
                with open(config_file, 'w', encoding='utf-8') as f:
                    json.dump(config, f, ensure_ascii=False, indent=4)
                    
                # 更新节点的UserRole数据
                session_data['config']['session_type'] = new_type
                session_data['config']['session_params'] = new_params
                item.setData(0, Qt.ItemDataRole.UserRole, session_data)
                
                self.log_manager.write_log(self.app_log, f"更新会话参数: {item.text(0)}, 类型: {new_type}", "Session")
            except Exception as e:
                self.log_manager.write_log(self.app_log, f"更新会话参数失败: {str(e)}", "Session")

    def create_new_session(self, parent_item):
        """创建新会话"""
        # 创建会话参数对话框
        params_dialog = SessionParamsDialog(self)
        if params_dialog.exec() != QDialog.DialogCode.Accepted:
            return
            
        # 获取会话类型和参数
        session_type, params = params_dialog.get_session_params()
        
        # 根据会话类型生成会话名称
        if session_type == "串口":
            device_name = params['port'].split('/')[-1]
            name = f"serial-{device_name}"
        else:  # SSH或Telnet
            name = params['host']
            
        # 检查是否存在重名，如果存在则添加数字后缀
        base_name = name
        counter = 1
        while self.check_session_name_exists(parent_item, name):
            name = f"{base_name}({counter})"
            counter += 1
        
        # 构建会话路径
        path_parts = []
        current_item = parent_item
        while current_item != self.topLevelItem(0):
            path_parts.insert(0, current_item.text(0))
            current_item = current_item.parent()
        path_parts.append(f"{name}.json")
        session_path = os.path.join(*path_parts)
        
        # 创建会话配置
        config = {
            "name": f"{name}.json",
            "type": "session",
            "session_type": session_type,
            "session_params": params
        }
        
        # 保存会话配置
        try:
            self.session_manager.save_session(session_path, config)
            self.log_manager.write_log(self.app_log, f"创建新会话: {name}, 类型: {session_type}", "Session")
        except Exception as e:
            self.log_manager.write_log(self.app_log, f"创建会话失败: {str(e)}", "Session")
            return
        
        # 添加会话节点
        item = QTreeWidgetItem(parent_item)
        item.setText(0, name)
        
        # 设置会话图标
        if session_type == "串口":
            item.setIcon(0, self.serial_icon)
        elif session_type == "SSH":
            item.setIcon(0, self.ssh_icon)
        elif session_type == "Telnet":
            item.setIcon(0, self.telnet_icon)
            
        # 设置会话数据
        session_data = {
            "path": session_path,
            "config": config
        }
        item.setData(0, Qt.ItemDataRole.UserRole, session_data)

    def delete_item(self, item):
        """删除节点"""
        # 获取会话数据
        session_data = item.data(0, Qt.ItemDataRole.UserRole)
        
        # 根据节点类型显示不同的确认消息
        if session_data and session_data['config']['type'] == 'session':
            confirm_msg = f"确定要删除会话 '{item.text(0)}' 吗？"
        else:
            confirm_msg = f"确定要删除文件夹 '{item.text(0)}' 吗？"
            if item.childCount() > 0:
                confirm_msg += "\n注意：文件夹中的所有会话也将被删除！"
        
        # 显示确认对话框
        from PySide6.QtWidgets import QMessageBox
        reply = QMessageBox.question(self, '确认删除', confirm_msg,
                                   QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                                   QMessageBox.StandardButton.No)
        
        if reply == QMessageBox.StandardButton.Yes:
            # 如果是会话节点，删除对应的配置文件
            if session_data and session_data['config']['type'] == 'session':
                config_file = os.path.join(self.session_manager.sessions_dir, session_data['path'])
                try:
                    os.remove(config_file)
                    self.log_manager.write_log(self.app_log, f"删除会话: {item.text(0)}", "Session")
                except Exception as e:
                    error_msg = f"删除配置文件失败: {str(e)}"
                    self.log_manager.write_log(self.app_log, f"删除会话失败: {error_msg}", "Session")
                    QMessageBox.warning(self, '删除失败', error_msg)
                    return
            
            # 从树形结构中移除节点
            parent = item.parent()
            if parent:
                parent.removeChild(item)
            else:
                self.takeTopLevelItem(self.indexOfTopLevelItem(item))

    def create_new_folder(self, parent_item):
        """新建分组"""
        # 获取新分组名称
        name, ok = QInputDialog.getText(self, "新建分组", "请输入分组名称：")
        if not ok or not name:
            return
            
        # 构建文件夹路径
        path_parts = []
        current_item = parent_item
        while current_item != self.topLevelItem(0):
            path_parts.insert(0, current_item.text(0))
            current_item = current_item.parent()
        
        # 检查是否存在重名并生成新名称
        base_name = name
        counter = 1
        folder_name = name
        while os.path.exists(os.path.join(self.session_manager.sessions_dir, *path_parts, folder_name)):
            folder_name = f"{base_name}({counter})"
            counter += 1
        
        # 更新最终的文件夹名称
        name = folder_name
        path_parts.append(name)
        folder_path = os.path.join(*path_parts) if path_parts else name
        
        try:
            # 创建文件夹
            full_path = os.path.join(self.session_manager.sessions_dir, folder_path)
            os.makedirs(full_path, exist_ok=True)
            
            # 创建分组节点
            new_folder = QTreeWidgetItem(parent_item)
            new_folder.setText(0, name)
            new_folder.setIcon(0, self.folder_icon)
            new_folder.setExpanded(True)
            
            self.log_manager.write_log(self.app_log, f"创建新分组: {name}", "Session")
        except Exception as e:
            self.log_manager.write_log(self.app_log, f"创建分组失败: {str(e)}", "Session")
            from PySide6.QtWidgets import QMessageBox
            QMessageBox.warning(self, '创建失败', f'创建分组失败: {str(e)}')
            return
            
    def check_session_name_exists(self, parent_item, name):
        """检查指定父节点下是否存在同名会话"""
        for i in range(parent_item.childCount()):
            child = parent_item.child(i)
            if child.text(0) == name:
                return True
        return False

    def rename_item(self, item):
        """重命名节点"""
        name, ok = QInputDialog.getText(self, "重命名", "请输入新的名称：")
        if not ok or not name:
            return
            
        # 获取节点数据
        session_data = item.data(0, Qt.ItemDataRole.UserRole)
        
        # 更新配置文件
        config_file = os.path.join(self.session_manager.sessions_dir, session_data['path'])
        with open(config_file, 'r', encoding='utf-8') as f:
            config = json.load(f)
        
        config['name'] = name
        
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, ensure_ascii=False, indent=4)
            
        # 更新节点的UserRole数据
        session_data['config']['name'] = name
        item.setData(0, Qt.ItemDataRole.UserRole, session_data)

    def dropEvent(self, event):
        """处理拖放事件"""
        if event.source() != self:
            event.ignore()
            return
            
        # 获取拖放的项目和目标位置
        item = self.currentItem()
        target = self.itemAt(event.pos())
        
        if not item or not target:
            event.ignore()
            return
            
        # 不允许将项目拖放到会话节点上
        target_data = target.data(0, Qt.ItemDataRole.UserRole)
        if target_data and target_data['config']['type'] == 'session':
            event.ignore()
            return
            
        # 获取源项目的数据
        item_data = item.data(0, Qt.ItemDataRole.UserRole)
        if not item_data:
            event.ignore()
            return
            
        # 构建新的路径
        old_path = item_data['path']
        new_parent_path = []
        current_item = target
        while current_item != self.topLevelItem(0):
            new_parent_path.insert(0, current_item.text(0))
            current_item = current_item.parent()
            
        new_path = os.path.join(*new_parent_path) if new_parent_path else ''
        new_path = os.path.join(new_path, os.path.basename(old_path))
        
        try:
            # 移动文件或目录
            old_full_path = os.path.join(self.session_manager.sessions_dir, old_path)
            new_full_path = os.path.join(self.session_manager.sessions_dir, new_path)
            
            # 确保目标目录存在
            os.makedirs(os.path.dirname(new_full_path), exist_ok=True)
            
            # 移动文件或目录
            import shutil
            shutil.move(old_full_path, new_full_path)
            
            # 更新项目数据
            item_data['path'] = new_path
            item.setData(0, Qt.ItemDataRole.UserRole, item_data)
            
            # 从原父节点移除并添加到新父节点
            parent = item.parent()
            if parent:
                parent.removeChild(item)
            target.addChild(item)
            
            event.accept()
            self.log_manager.write_log(self.app_log, f"移动会话: {item.text(0)} 到 {target.text(0)}", "Session")
        except Exception as e:
            self.log_manager.write_log(self.app_log, f"移动会话失败: {str(e)}", "Session")
            event.ignore()

class SessionParamsDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
            
    def setup_ui(self):
        self.setWindowTitle("会话参数设置")
        layout = QVBoxLayout(self)
        
        # 会话类型选择
        type_layout = QHBoxLayout()
        type_label = QLabel("会话类型：")
        self.type_combo = QComboBox()
        self.type_combo.addItems(["串口", "SSH", "Telnet"])
        self.type_combo.currentTextChanged.connect(self.on_type_changed)
        type_layout.addWidget(type_label)
        type_layout.addWidget(self.type_combo)
        
        # 参数表单
        self.form_layout = QFormLayout()
        
        # 按钮
        button_layout = QHBoxLayout()
        self.ok_button = QPushButton("确定")
        self.cancel_button = QPushButton("取消")
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(type_layout)
        layout.addLayout(self.form_layout)
        layout.addLayout(button_layout)
        
        # 初始化串口参数表单
        self.on_type_changed("串口")
            
    def on_type_changed(self, session_type):
        # 清除现有表单
        while self.form_layout.count():
            item = self.form_layout.takeAt(0)
            if item.widget():
                item.widget().deleteLater()
        
        # 根据会话类型添加对应的参数表单
        if session_type == "串口":
            self.add_serial_params()
        elif session_type == "SSH":
            self.add_ssh_params()
        elif session_type == "Telnet":
            self.add_telnet_params()
                
    def add_serial_params(self):
        self.port = QComboBox()
        # 获取可用串口列表
        ports = [port.device for port in serial.tools.list_ports.comports()]
        self.port.addItems(ports if ports else ["无可用串口"])
        self.baudRate = QComboBox()
        self.baudRate.addItems(["9600", "19200", "38400", "57600", "115200"])
        self.form_layout.addRow("端口：", self.port)
        self.form_layout.addRow("波特率：", self.baudRate)
            
    def add_ssh_params(self):
        self.host = QLineEdit()
        self.port = QLineEdit("22")
        self.username = QLineEdit()
        self.password = QLineEdit()
        self.password.setEchoMode(QLineEdit.EchoMode.Password)
        self.form_layout.addRow("主机：", self.host)
        self.form_layout.addRow("端口：", self.port)
        self.form_layout.addRow("用户名：", self.username)
        self.form_layout.addRow("密码：", self.password)
            
    def add_telnet_params(self):
        self.host = QLineEdit()
        self.port = QLineEdit("23")
        self.form_layout.addRow("主机：", self.host)
        self.form_layout.addRow("端口：", self.port)
            
    def get_session_params(self):
        session_type = self.type_combo.currentText()
        params = {}
        
        if session_type == "串口":
            params.update({
                'port': self.port.currentText(),
                'baudRate': self.baudRate.currentText()
            })
        elif session_type == "SSH":
            params.update({
                'host': self.host.text(),
                'port': self.port.text(),
                'username': self.username.text(),
                'password': self.password.text()
            })
        elif session_type == "Telnet":
            params.update({
                'host': self.host.text(),
                'port': self.port.text()
            })
            
        return session_type, params